package frobagroup.services.backstage.impl;

import frobagroup.entities.backstage.Comment;
import frobagroup.entities.backstage.ImageText;
import frobagroup.entities.backstage.Product;
import frobagroup.entities.frontEnd.ShoppingCart;
import frobagroup.entities.frontEnd.UserProfile;
import frobagroup.pagination.PageableImpl;
import frobagroup.pagination.Pagination;
import frobagroup.repositories.backstage.CommentRepository;
import frobagroup.repositories.backstage.ImageTextRepository;
import frobagroup.repositories.backstage.ProductRepository;
import frobagroup.repositories.frontEnd.ShoppingCartRepository;
import frobagroup.repositories.frontEnd.UserProfileRepository;
import frobagroup.services.backstage.StaffProductService;
import frobagroup.utils.Constants;
import frobagroup.utils.fileUtils.FileUploadServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by Tinsley on 2018/5/16.
 */
@Service
public class StaffProductServiceImpl implements StaffProductService {

    @Autowired
    private ProductRepository productRepository;
    @Autowired
    private FileUploadServer fileUploadServer;
    @Autowired
    private ImageTextRepository imageTextRepository;
    @Autowired
    private UserProfileRepository userProfileRepository;
    @Autowired
    private CommentRepository commentRepository;
    @Autowired
    private ShoppingCartRepository shoppingCartRepository;

    @Override
    public Product addOrEditProduct(Product product, String sId)throws Exception {

        if (StringUtils.isEmpty(product.getId())){

            product.setSId(sId);
            product.setCommitTime(new Date());
            product.setBrowseNumbers(1);
//            if(!StringUtils.isEmpty(productPic))
//                product.setProductPic(fileUploadServer.uploadFileToCloud(productPic));

        }else{
            product.setUpdateTime(new Date());
//            if(!StringUtils.isEmpty(productPic)) {
//                fileUploadServer.deletePublicFile(product.getProductPic());
//                product.setProductPic(fileUploadServer.uploadFileToCloud(productPic));
//            }
        }

        return productRepository.save(product);
    }

    @Override
    public Product addOrEditProductPic(MultipartFile pic, String pId, String sId) throws Exception{

        Product product = productRepository.findOne(pId);
        if (!StringUtils.isEmpty(product.getProductPic()))
            fileUploadServer.deletePublicFile(product.getProductPic());
        String url = fileUploadServer.uploadFileToCloud(pic);
        product.setProductPic(url);
        List<ShoppingCart> shoppingCarts =  shoppingCartRepository.findByPId(pId);
        if (shoppingCarts.size()>0) {
            shoppingCarts = shoppingCarts.stream().map(e -> {
                e.setProductPic(url);
                return e;
            }).collect(Collectors.toList());
            shoppingCartRepository.save(shoppingCarts);
        }
        return productRepository.save(product);
    }

    @Override
    public Product editImageText(MultipartFile pic, String sId, String content, String pId, String order, String type, String itId) throws Exception {
        if(StringUtils.isEmpty(pId)){
            Product product = new Product();
            product.setSId(sId);
            product.setCommitTime(new Date());
            product.setStatus("inactive");
            product.setType(type);
            ImageText imageText = new ImageText();
            if (!StringUtils.isEmpty(pic))
                imageText.setPic(fileUploadServer.uploadFileToCloud(pic));
            imageText.setContent(content);
            imageText.setOrder(Integer.parseInt(order));
            ImageText it = imageTextRepository.save(imageText);
            product.getImgIds().add(it.getId());
            product.setUpdateTime(new Date());
            return productRepository.save(product);
        }else{
            Product product = productRepository.findOne(pId);
            if (StringUtils.isEmpty(itId)){
                List<ImageText> imageTexts = (List<ImageText>)imageTextRepository.findAll(product.getImgIds());
                for (ImageText i:imageTexts){
                    if (Objects.equals(order,String.valueOf(i.getOrder()))){
                        product.setStatus(String.valueOf(Constants.RESPONSE_STATUS_FAILURE));
                        return product;
                    }
                }
                ImageText imageText = new ImageText();
                imageText.setOrder(Integer.parseInt(order));
                imageText.setContent(content);
                if (!StringUtils.isEmpty(pic))
                    imageText.setPic(fileUploadServer.uploadFileToCloud(pic));
                ImageText it = imageTextRepository.save(imageText);
                product.getImgIds().add(it.getId());
            }else{
                ImageText imageText = imageTextRepository.findOne(itId);
                imageText.setContent(content);
                if (!StringUtils.isEmpty(pic)){
                    imageText.setPic(fileUploadServer.uploadFileToCloud(pic));
                }
                ImageText it = imageTextRepository.save(imageText);
                product.getImgIds().add(it.getId());
            }
            product.setUpdateTime(new Date());
            return productRepository.save(product);
        }
    }

    @Override
    public void removeImageText(String pic, String sId, String pId, String itId) throws Exception {
        Product product = productRepository.findOne(pId);
        product.getImgIds().remove(itId);
        productRepository.save(product);
        fileUploadServer.deletePublicFile(pic);
        imageTextRepository.delete(itId);
    }

    @Override
    public ImageText removeImageTextPic(String id, String sId)throws Exception {
        ImageText imageText = imageTextRepository.findOne(id);
        fileUploadServer.deletePublicFile(imageText.getPic());
        imageText.setPic(null);
        return imageTextRepository.save(imageText);
    }

    @Override
    public Pagination findProducts(Pagination pagination) {
        String sort = Objects.isNull(pagination.getSort()) ? "commitTime" : pagination.getSort();
        PageableImpl pageable = new PageableImpl(pagination.getPageNumber(),pagination.getPageSize(),
                new Sort(Objects.equals(Sort.Direction.DESC.name(),pagination.getDir()) ? Sort.Direction.DESC:Sort.Direction.ASC,sort));
        Page<Product> pages;
        if(Objects.equals(pagination.getConditions().size(),0))
            pages = productRepository.findAll(pageable);
        else
            pages = productRepository.findByTypeAndStatus((String)pagination.getConditions().get("type"),
                    (String)pagination.getConditions().get("status"), pageable);
        pagination.setContent(pages.getContent());
        pagination.setTotal(pages.getTotalElements());
        return pagination;
    }

    @Override
    public Map<String, Object> findProductDetial(String id, HttpServletRequest request) {
        Map params = new HashMap();
        Product product = productRepository.findOne(id);
        if (product.getImgIds().size()>=1){
            List<ImageText> imageTextList = (List<ImageText>)imageTextRepository.findAll(product.getImgIds());
            params.put("imageTextList",imageTextList.stream().sorted(Comparator.comparing(ImageText::getOrder))
                    .collect(Collectors.toList()));
        }
        if (!StringUtils.isEmpty(product.getRelatedProductsIds()))
            params.put("relatedProducts",productRepository.findAll(product.getRelatedProductsIds()));

//        if (!StringUtils.isEmpty(article.getVideoId()))
//            params.put("video",videoRepository.findOne(article.getVideoId()));
//        if (!StringUtils.isEmpty(article.getAudioId()))
//            params.put("audio",audioRepository.findOne(article.getAudioId()));
        List<Comment> comments;
        if (!StringUtils.isEmpty(request.getAttribute("id"))){

            String userId = (String)request.getAttribute("id");
            comments = commentRepository.findByPIdAndStatus(id,"active");
            if (comments.size()>0) {
                comments.stream().map(e -> {
                    if (e.getCommentThumbsUpIds().contains(userId))
                        e.setWhetherCommentThumbsUp(Boolean.TRUE);
                    return e;
                }).collect(Collectors.toList());
            }

        }else
            comments = commentRepository.findByPId(id);
        if(comments.size()>0)
            comments = comments.stream().sorted(Comparator.comparing(Comment::getCommentDate).reversed()).collect(Collectors.toList());

        params.put("comments",comments);
        params.put("product",product);
        return params;
    }

    @Override
    public Product comment(String pId, Comment comment, String uId) {
        Product product = productRepository.findOne(pId);
        UserProfile userProfile= userProfileRepository.findByUId(uId);
        comment.setStatus("active");
        comment.setCommentDate(new Date());
        comment.setCommentorId(uId);
        comment.setPId(product.getId());
        comment.setAvatarUrl(userProfile.getPhotoPic());
        comment.setCommentorName(userProfile.getFirstName() +" "+userProfile.getLastName());
        Comment c = commentRepository.save(comment);
        product.getCommentIds().add(c.getId());
        return productRepository.save(product);
    }

    @Override
    public List<ImageText> adjustImageTextOrder(Map<String, List<ImageText>> its, String pId) {

        Product product = productRepository.findOne(pId);
        List<ImageText> imageTexts = (List<ImageText>)imageTextRepository.findAll(product.getImgIds());
        if (!Objects.equals(imageTexts.size(),its.get("its").size()))
            return new ArrayList<>();
        return imageTextRepository.save(its.get("its"));
    }

    @Override
    public Product addOrEditRelatedProduct(Product product) {
        return productRepository.save(product);
    }
}
